package jfxtras.scene.control;

import java.util.Arrays;
import java.util.List;

/**
 * 
 * @author User
 *
 * @param <T>
 */
public class SpinnerXDataProviderList<T>
implements SpinnerXDataProvider<T, Integer>
{
	/**
	 * 
	 * @param list
	 */
	public SpinnerXDataProviderList(List<T> list)
	{
		this.list = list;
	}
	protected List<T> list;
	
	/**
	 * 
	 * @param idx
	 * @return
	 */
	@Override
	public Integer getPreviousIndex(Integer idx)
	{
		// null returns first index
		if (idx == null) return 0;
		
		// decrement				
		if (idx == 0) return null; // no previous index
		Integer lIndex = idx - 1;
		return lIndex;
	}

	/**
	 * 
	 * @param idx
	 * @return
	 */
	@Override
	public Integer getNextIndex(Integer idx)
	{
		// null returns last index
		if (idx == null) return list.size() - 1;
		
		// increment
		if (idx == (list.size() - 1)) return null; // no next index
		Integer lIndex = idx + 1;
		return lIndex;
	}

	/**
	 * 
	 */
	@Override
	public T getValue(Integer idx)
	{
		return list.get(idx.intValue());
	}
	
	/**
	 * 
	 */
	@Override
	public Integer getIndex(T value)
	{
		int lIdx = list.indexOf(value);
		if (lIdx < 0) return null; // not found
		return Integer.valueOf(lIdx);
	}

	/**
	 * 
	 */
	@Override
	public Integer addValue(T value)
	{
		list.add(value);
		return list.size();
	}

	// ======================================================================================================
	// CONVENIENCE
	
	/**
	 * 
	 * @param list
	 * @return
	 */
	static public <T> SpinnerXDataProviderList<T> list(final T... list)
	{
		return new SpinnerXDataProviderList<T>(Arrays.asList(list));
	}
}